package com.atguigu.gmall.controller;

import com.atguigu.gmall.beans.KeywordStats;
import com.atguigu.gmall.beans.ProductStats;
import com.atguigu.gmall.beans.ProvinceStats;
import com.atguigu.gmall.beans.VisitorStats;
import com.atguigu.gmall.service.KeywordStatsService;
import com.atguigu.gmall.service.ProductStatsService;
import com.atguigu.gmall.service.ProvinceStatsService;
import com.atguigu.gmall.service.VisitorStatsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 大屏展示控制类
 * @Author: tiancy
 * @Create: 2021/11/26
 */
@RestController
@RequestMapping("/api/sugar")
public class ProductTopicSugarController {
    @Autowired
    private ProductStatsService productStatsService;

    @Autowired
    private ProvinceStatsService provinceStatsService;

    @Autowired
    private KeywordStatsService keywordStatsService;

    @Autowired
    private VisitorStatsService visitorStatsService;

    /*
        实现热词云
        http://localhost:8070/api/sugar/keyword?date=20211210&limit=5
     */
    @RequestMapping("/keyword")
    public String getKeyword(
            @RequestParam(value = "date", defaultValue = "0") Integer date,
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {

        if (date == 0) {
            date = now();
        }

        List<KeywordStats> keywordStatsList = keywordStatsService.getKeyword(date, limit);
        StringBuilder jsonB = new StringBuilder("{\"status\": 0,\"data\": [");
        for (int i = 0; i < keywordStatsList.size(); i++) {
            KeywordStats keywordStats = keywordStatsList.get(i);
            jsonB.append("{\"name\": \"" + keywordStats.getKeyword() + "\",\"value\": " + keywordStats.getCt() + "}");
            if (i < keywordStatsList.size() - 1) {
                jsonB.append(",");
            }
        }
        jsonB.append("]}");
        return jsonB.toString();
    }

    /*
        统计每个小时的 uv、pv、独立会话数
        http://localhost:8070/api/sugar/hr?date=20211210
     */
    @RequestMapping("/hr")
    public String getVisitorStatsByHr(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }

        List<VisitorStats> visitorStatsList = visitorStatsService.getVisitorStatsByHr(date);

        VisitorStats[] visitorStatsArr = new VisitorStats[24];

        for (VisitorStats visitorStats : visitorStatsList) {
            visitorStatsArr[visitorStats.getHr()] = visitorStats;
        }

        List hrList = new ArrayList();
        List pvList = new ArrayList();
        List uvList = new ArrayList();
        List svList = new ArrayList();

        //对数组进行遍历   取出某天每一个小时的访问情况
        for (int hr = 0; hr < visitorStatsArr.length; hr++) {
            VisitorStats visitorStats = visitorStatsArr[hr];
            if (visitorStats != null) {
                pvList.add(visitorStats.getPv_ct());
                uvList.add(visitorStats.getUv_ct());
                svList.add(visitorStats.getSv_ct());
            } else {
                pvList.add(0L);
                uvList.add(0L);
                svList.add(0L);
            }
            hrList.add(String.format("%02d", hr));
        }

        //拼接字符串
        String json = "{\"status\":0,\"data\":{" + "\"categories\":" +
                "[\"" + StringUtils.join(hrList, "\",\"") + "\"],\"series\":[" +
                "{\"name\":\"uv\",\"data\":[" + StringUtils.join(uvList, ",") + "]}," +
                "{\"name\":\"pv\",\"data\":[" + StringUtils.join(pvList, ",") + "]}," +
                "{\"name\":\"sv\",\"data\":[" + StringUtils.join(svList, ",") + "]}]}}";
        return json;


    }
    /*
        新老访客比较
        http://localhost:8070/api/sugar/isnew?date=20211210
     */
    @RequestMapping("/isnew")
    public String getVisitorStatsByIsNew(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }

        VisitorStats newVisitorStats = new VisitorStats();
        VisitorStats oldVisitorStats = new VisitorStats();

        List<VisitorStats> visitorStatsList = visitorStatsService.getVisitorStatsByIsNew(date);
        for (VisitorStats visitorStats : visitorStatsList) {
            if (visitorStats.getIs_new().equals("1")) {
                newVisitorStats = visitorStats;
            } else {
                oldVisitorStats = visitorStats;
            }
        }
        String json = "{\"status\":0,\"data\":{\"combineNum\":1,\"columns\":" +
                "[{\"name\":\"类别\",\"id\":\"type\"}," +
                "{\"name\":\"新用户\",\"id\":\"new\"}," +
                "{\"name\":\"老用户\",\"id\":\"old\"}]," +
                "\"rows\":" +
                "[{\"type\":\"用户数(人)\"," +
                "\"new\": " + newVisitorStats.getUv_ct() + "," +
                "\"old\":" + oldVisitorStats.getUv_ct() + "}," +
                "{\"type\":\"总访问页面(次)\"," +
                "\"new\":" + newVisitorStats.getPv_ct() + "," +
                "\"old\":" + oldVisitorStats.getPv_ct() + "}," +
                "{\"type\":\"跳出率(%)\"," +
                "\"new\":" + newVisitorStats.getUjRate() + "," +
                "\"old\":" + oldVisitorStats.getUjRate() + "}," +
                "{\"type\":\"平均在线时长(秒)\"," +
                "\"new\":" + newVisitorStats.getDurPerSv() + "," +
                "\"old\":" + oldVisitorStats.getDurPerSv() + "}," +
                "{\"type\":\"平均访问页面数(人次)\"," +
                "\"new\":" + newVisitorStats.getPvPerSv() + "," +
                "\"old\":" + oldVisitorStats.getPvPerSv()
                + "}]}}";
        return json;

    }

    /*
        每个省份每天销售总额
        http://localhost:8070/api/sugar/province?date=20211210&limit=5
     */
    @RequestMapping("/province")
    public String getProvinceStats(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        List<ProvinceStats> provinceStatsList = provinceStatsService.getProvinceStats(date);

        StringBuilder jsonB = new StringBuilder("{\"status\": 0,\"data\": {\"mapData\": [");
        for (int i = 0; i < provinceStatsList.size(); i++) {
            ProvinceStats provinceStats = provinceStatsList.get(i);
            jsonB.append(" {\"name\": \"" + provinceStats.getProvince_name() + "\",\"value\": " + provinceStats.getOrder_amount() + "}");
            if (i < provinceStatsList.size() - 1) {
                jsonB.append(",");
            }
        }
        jsonB.append("],\"valueName\": \"交易额\"}}");
        return jsonB.toString();
    }


    // TODO 4、每天每个spu总销售额
    /*
        数据格式 :
     */
    // http://localhost:8070/api/sugar/spu?date=20211210&limit=5
    @RequestMapping("/spu")
    public String getProductStatsBySpu(@RequestParam(value = "date", defaultValue = "0") Integer date) {

        if (date == 0) {
            date = now();
        }

        List<ProductStats> productStatsList = productStatsService.getProductStatsBySpu(date);
        StringBuilder jsonB = new StringBuilder("{\"status\": 0,\"data\": { \"columns\": [{\"name\": \"商品名称\", \"id\": \"name\"},{\"name\": \"交易额\",\"id\": \"amount\"},{\"name\": \"订单数\",\"id\": \"ct\"}],\"rows\": [");

        for (int i = 0; i < productStatsList.size(); i++) {
            ProductStats productStats = productStatsList.get(i);
            if (i >= 1) {
                jsonB.append(",");
            }
            jsonB.append("{\"name\": \"" + productStats.getSpu_name() + "\"," +
                    "\"amount\": " + productStats.getOrder_amount() + "," +
                    "\"ct\": " + productStats.getOrder_ct() + "}");

        }
        jsonB.append("]}}");

        return jsonB.toString();
    }

    // TODO 3、每天每个品类销售额
    /*
        这里给定了两种实现思路
        http://localhost:8070/api/sugar/category3?date=20211210&limit=5
     */
    @RequestMapping("/category3")
    public Object getProductStatsByCategory3(
            @RequestParam(value = "date", defaultValue = "0") Integer date,
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {

        if (date == 0) {
            date = now();
        }

        Map resMap = new HashMap();
        List dataList = new ArrayList();
        resMap.put("status", 0);
        List<ProductStats> productStatsList = productStatsService.getProductStatsByCategory3(date, limit);
        for (ProductStats productStats : productStatsList) {
            Map dataMap = new HashMap();
            dataMap.put("name", productStats.getCategory3_name());
            dataMap.put("value", productStats.getOrder_amount());
            dataList.add(dataMap);
        }
        resMap.put("data", dataList);

        return resMap;
    }
    /*
        数据格式 :
        {
          "status": 0,
          "data": [
            {
              "name": "PC",
              "value": 97
            },
            {
              "name": "iOS",
              "value": 50
            }
          ]
        }
        实现思路一 : `data属性中是一个数组`,数组中的每一项,我们可以用`List<ProductStats>`中的每个对象中的每个属性来填充.
        在写的时候,需要注意 : 判断当前集合中的元素是否为最后一个或者是否为首个,如果是,注意拼接 `,`

     */
    /*@RequestMapping("/category3")
    public String getProductStatsByCategory3(
        @RequestParam(value = "date", defaultValue = "0") Integer date,
        @RequestParam(value = "limit", defaultValue = "20") Integer limit) {

        if (date == 0) {
            date = now();
        }

        StringBuilder jsonB = new StringBuilder("{\"status\": 0,\"data\": [");
        List<ProductStats> productStatsList = productStatsService.getProductStatsByCategory3(date, limit);
        for (int i = 0; i < productStatsList.size(); i++) {
            ProductStats productStats = productStatsList.get(i);
            jsonB.append("{\"name\": \""+productStats.getCategory3_name()+"\",\"value\": "+productStats.getOrder_amount()+"}");
            if(i < productStatsList.size() - 1){
                jsonB.append(",");
            }
        }

        jsonB.append("]}");
        return jsonB.toString();
    }*/


    // TODO 2、每日每个品牌总金额的统计
    /*
        http://localhost:8070/api/sugar/tm?date=20211210&limit=5
     */
    @RequestMapping("/tm")
    public String getProductStatsByTm(
            @RequestParam(value = "date", defaultValue = "0") Integer date,
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
        //对参数date为null的情况进行处理
        if (date == 0) {
            date = now();
        }
        List<ProductStats> productStatsList = productStatsService.getProductStatsByTm(date, limit);
        /*
            这里需要考虑如何将获取的结果,拼接成`sugar`想要的json格式.并且我们在Controller中已经使用了`RestController`,表名SpringMVC会将我们的查询结果,自定转化为json格式.
            sugar想要的数据格式 :
            {
              "status": 0,
              "data": {
                "categories": [
                  "苹果",
                  "三星",
                  "华为"
                ],
                "series": [
                  {
                    "name": "当前品牌销售额",
                    "data": [
                      9447,
                      7097,
                      9275
                    ]
                  }
                ]
              }
            }
          我们仅仅需要将`categories`属性中的数组替换成查询的`productStatsList`中的手机品牌列表,并按照`逗号`分割开.处理方式如下: 直接使用字符串拼接,需要替换的动态查询结果,使用`StringUtils.join`处理.
         */
        List tm_names = new ArrayList<>();
        List amountList = new ArrayList<>();
        for (ProductStats productStats : productStatsList) {
            tm_names.add(productStats.getTm_name());
            amountList.add(productStats.getOrder_amount());
        }
        /*
            {"status": 0,"data": {"categories": ["苹果","三星","华为"],"series": [{"name": "当前品牌销售额","data": [9447,7097,9275]}]}}
            "苹果","三星","华为" : 这部分的数据需要我们通过查询结果填充, 这里的处理方式为 直接使用 import org.apache.commons.lang3.StringUtils.join()工具类进行填充.

            StringUtils.join(List,"连接符") ==> 这里的连接符为 "\,"\
         */
        String json = "{\"status\": 0,\"data\": {\"categories\": [\"" + StringUtils.join(tm_names, "\",\"") + "\"]," +
                "\"series\": [{\"name\": \"当前品牌销售额\",\"data\": [" + StringUtils.join(amountList, ",") + "]}]}}";
        //System.out.println(json);
        return json;
    }

    // TODO 1、每日商品总金额统计
    /*
        http://localhost:8070/api/sugar/gmv?date=20211210
        其中 `date` 参数可以不传,会取今天作为 默认值.
     */
    @RequestMapping("/gmv")
    public String getGMV(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        //对参数date为null的情况进行处理
        if (date == 0) {
            date = now();
        }
        BigDecimal gmv = productStatsService.getGMV(date);
        String json = "{\"status\": 0,\"data\": " + gmv + "}";
        return json;
    }

    //获取今天日期
    private Integer now() {
        String yyyyMMdd = DateFormatUtils.format(new Date(), "yyyyMMdd");
        return Integer.valueOf(yyyyMMdd);
    }
}